package com.example.dell.workactivity.mvp;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dell.basic.BasicBasicActivity;
import com.example.dell.basicapplication.R;
import com.example.dell.utils.RealPathFromUriUtils;

import java.util.List;
import java.util.Vector;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class SaoMaActivity extends BasicBasicActivity implements QRCodeView.Delegate {


    private static final int           MY_CAMERA           = 100;
    private static final int           MY_EXTERNAL_STORAGE = 101;
    private static final int           REQUEST_PICK_IMAGE  = 111;
    private              ZXingView     mQRCodeView;
    private              ImageView     mSaoLight;
    private              List<Boolean> haveLight           = new Vector<>();
    public               boolean       hasClosed           = false; // 定义开关状态，状态为false，打开状态，状态为true，关闭状态

    @Override
    protected int setContentSuccessView() {
        return R.layout.activity_sao_ma;
    }

    @Override
    protected void initView(View view) {

        getBasicBar().setVisibility(View.GONE);
        haveLight.clear();
        mQRCodeView = (ZXingView) view.findViewById(R.id.zxingview);
        mQRCodeView.setDelegate(SaoMaActivity.this);
        mSaoLight = (ImageView) view.findViewById(R.id.sao_ma_light);
        view.findViewById(R.id.fresh_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //打开相册
        view.findViewById(R.id.picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //检查版本是否大于M
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(SaoMaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SaoMaActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_EXTERNAL_STORAGE);
                    } else {
                        photoPture();
                    }
                } else {
                    photoPture();
                }
            }
        });

        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(SaoMaActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(SaoMaActivity.this,
                        new String[]{Manifest.permission.CAMERA},
                        MY_CAMERA);

            }
        }
        //初始化界面的默认状态
        hasClosed = true;
        mSaoLight.setImageResource(R.mipmap.light_close);
        mQRCodeView.closeFlashlight();
        //Android 7.0开启闪光灯
        // haveLight判断是否有闪光灯 false为有闪光灯
        // hasClosed 是否关闭闪光灯  ture为关闭闪光灯
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                //获取CameraManager
                CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                //获取当前手机所有摄像头设备ID
                String[] ids = mCameraManager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
                    //查询该摄像头组件是否包含闪光灯
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    if (!flashAvailable) {
                        haveLight.add(false);
                    } else {
                        haveLight.add(true);
                    }
                }
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        } else {
            //判断是否有闪光
            if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
                haveLight.add(true);
            }

        }
        //扫码开关灯
        mSaoLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (haveLight.contains(true)) {
                    if (hasClosed) {
                        mQRCodeView.openFlashlight();
                        mSaoLight.setImageResource(R.mipmap.light_open);
                    } else {
                        mQRCodeView.closeFlashlight();
                        mSaoLight.setImageResource(R.mipmap.light_close);
                    }
                    hasClosed = !hasClosed;
                } else {
                    vibrate();
                    Toast.makeText(SaoMaActivity.this, "您的手机没有闪光灯", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    @Override
    protected void initData() {
        autoShowPager(true, "");
    }


    @Override
    protected void onStart() {
        super.onStart();
        mQRCodeView.startCamera();
        mQRCodeView.showScanRect();
    }


    @Override
    protected void onResume() {
        super.onResume();
        //        mQRCodeView.startSpot();
        mQRCodeView.startSpotAndShowRect();
    }


    @Override
    protected void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        //扫码成功后，开启震动一下的功能
        mQRCodeView.stopSpotAndHiddenRect();
        vibrate();
        dealCode(result);
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(SaoMaActivity.this, "打开相机出错", Toast.LENGTH_SHORT).show();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(SaoMaActivity.this, permissions[0]);
                if (!showRequestPermission) {
                    Intent intent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                    finish();
                    return;
                } else {
                    finish();
                }
            }
        } else if (requestCode == MY_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                photoPture();
            } else {
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(SaoMaActivity.this, permissions[0]);
                if (!showRequestPermission) {
                    Intent intent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                    finish();
                    return;
                } else {
                    finish();
                }
            }


        }
    }

    /**
     * 选择相册
     */
    private void photoPture() {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_PICK_IMAGE) {
                if (data != null) {
                    final String picturePath = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
            /*
            这里为了偷懒，就没有处理匿名 AsyncTask 内部类导致 Activity 泄漏的问题
            请开发在使用时自行处理匿名内部类导致Activity内存泄漏的问题，处理方式可参考 https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
             */
                    new AsyncTask<Void, Void, String>() {
                        @Override
                        protected String doInBackground(Void... params) {
                            return QRCodeDecoder.syncDecodeQRCode(picturePath);
                        }

                        @Override
                        protected void onPostExecute(String result) {
                            if (TextUtils.isEmpty(result)) {
                                vibrate();
                                Toast.makeText(SaoMaActivity.this, "未发现二维码", Toast.LENGTH_SHORT).show();
                            } else {
                                vibrate();
                                dealCode(result);
                            }
                        }
                    }.execute();

                } else {
                    vibrate();
                    Toast.makeText(this, "图片损坏，请重新选择二维码", Toast.LENGTH_SHORT).show();
                }

            }

        }
    }

    /**
     * @param result 处理二维码
     */
    private void dealCode(String result) {
        if (isConnected()) {
            if (result.contains("932edu.com")) {
                String type = Uri.parse(result).getQueryParameter("type");
                String mId = Uri.parse(result).getQueryParameter("qId");
                if (type != null && mId != null) {
                    //行测
                    if (TextUtils.equals(type, "1")) {
                        //                        Intent intent = new Intent(SaoMaActivity.this, AnalysisActivity.class);
                        //                        intent.putExtra("id", mId);
                        //                        intent.putExtra("type", 3);
                        //                        startActivity(intent);
                        //申论
                    } else if (TextUtils.equals(type, "2")) {
                        //                        Intent intent = new Intent(SaoMaActivity.this, AnalysisActivity.class);
                        //                        intent.putExtra("id", mId);
                        //                        intent.putExtra("type", 3);
                        //                        startActivity(intent);
                    } else {
                        Toast.makeText(SaoMaActivity.this, "无法识别此二维码，请扫描老吴公考专用二维码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(SaoMaActivity.this, "无法识别此二维码，请扫描老吴公考专用二维码", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(SaoMaActivity.this, "无法识别此二维码，请扫描老吴公考专用二维码", Toast.LENGTH_SHORT).show();
            }
        } else {
            //处理失败后重新开始扫码
            mQRCodeView.startSpotAndShowRect();
            Toast.makeText(SaoMaActivity.this, "当前网络状态不佳,请检查网络", Toast.LENGTH_SHORT).show();
        }
    }
}
